<?php


namespace app\api\controller;


use addons\epay\library\Service;
use app\common\controller\Api;
use app\common\controller\Util;
use think\Db;
use think\Env;
use think\Exception;
use think\Hook;
use function GuzzleHttp\Psr7\str;


class Bizorder extends Api

{


    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['checkOrders', 'toPay'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];


    public function test()
    {
        phpinfo();
    }

    /**
     * Notes: 添加课程到购物车
     * User: zhao
     * Date: 2020/8/17
     * Time: 10:16
     */
    public function add2car()
    {
        $param = $this->request->post();
        $user_id = $this->auth->id;
        $course_id = $param['course_id'];
        if (!$course_id) {
            $this->error("course_id is empty");
        }
        $course = Db::name('course')->where('id', $course_id)->find();
        if (!$course) {
            $this->error("课程不存在");
        }
        $student = Db::name("student")->where("user_id", $user_id)->find();
        if (!$student) {
            $this->error("当前用户不存在");
        }
        Db::startTrans();
        try {
            //直接获取购物车
            $mygoods = Db::name('order_car_item')->where('student_id', $student['id'])->where('course_id', $course_id)->find();
            if ($mygoods) {
                throw new Exception('不能重复添加到购物车');
            }
            //校验是否已经购买过该课程
            $myOrderWhere['userId'] = $student['id'];
            $myOrderWhere['courseId'] = $course_id;
            $myOrderWhere['status'] = array('in', 'created,paid');
            $has = Db::name('order')->where($myOrderWhere)->find();
            if ($has) {
                if ($has['status'] === 'created') {
                    throw new Exception($course['title'] . '订单已经创建，请支付');
                }
                throw new Exception($course['title'] . '已经报名了');
            }
            $course_num = $course['course_num'];
            $student_num = $course['student_num'];
            if ($course['type_status'] == 1 && $student_num >= $course_num) {
                throw new Exception('课程订购人数已满');
            }
            $carItem['student_id'] = $student['id'];
            $carItem['course_id'] = $course_id;
            $carItem['course_name'] = $course['title'];
            $sql = Db::name('order_car_item')->insert($carItem);
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->error($e->getMessage());
        }
        $this->success('添加成功');
    }

    /**
     * @Notes:
     * @Author: zhao
     * @Date: 2020/9/7
     * @Time: 17:15
     * @Interface publiclesson
     * 公开课报名
     */
    public function publiclesson()
    {
        $param = $this->request->post();
        $user_id = $this->auth->id;
        $course_id = $param['course_id'];
        if (!$course_id) {
            $this->error("课程不存在");
        }
        $course = Db::name('course')->where('id', $course_id)->find();
        if (!$course) {
            $this->error('课程不存在');
        }
        if ('3' !== $course['type_status']) {
            $this->error('该课程不是公开课');
        }
        $student = Db::name("student")->where("user_id", $user_id)->find();
        if (!$student) {
            $this->error("当前用户不存在");
        }
        $myOrderWhere['userId'] = $student['id'];
        $myOrderWhere['courseId'] = $course_id;
        $myOrderWhere['status'] = array('in', 'created,paid');
        $has = Db::name('order')->where($myOrderWhere)->find();
        if ($has) {
            if ($has['status'] === 'created') {
                return $this->error($course['title'] . '订单已经创建，请支付');
            }
            return $this->error($course['title'] . '已经报名了');
        }
        try {
            Db::startTrans();
            $order['coupon_id'] = '';
            $order['courseId'] = $course['id'];
            $order['sn'] = Util::getOrderNumber();
            $order['userId'] = $student['id'];
            $order['create_time'] = Util::getNowDateTime();
            $order['title'] = $course['title'];
            $order['batch_id'] = Util::getOrderNumber();
            $order['status'] = 'paid';
            $order['userId'] = $student['id'];
            $order['amount'] = 0;
            Db::name('order')->insert($order);
            $course_num = $course['course_num'];
            $student_num = $course['student_num'];
            if ($course['type_status'] == 1 && $student_num >= $course_num) {
                throw new Exception('课程订购人数已满');
            }
            $student_num += 1;
            $courseUpdate['id'] = $order['courseId'];
            $courseUpdate['student_num'] = $student_num;
            Db::name('course')->update($courseUpdate);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            if ($e->getMessage()) {
                return $this->error($e->getMessage());
            }
        }
        return $this->success('报名成功');
    }

    /**
     * @Notes:
     * @Author: zhao
     * @Date: 2020/9/1
     * @Time: 14:15
     * @Interface removeCar
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 移除购物车
     */
    public function removeCar()
    {
        $param = $this->request->post();
        $user_id = $this->auth->id;
        $course_id = $param['course_id'];
        if (!$course_id) {
            $this->error("课程不存在");
        }
        $course = Db::name('course')->where('id', $course_id)->find();
        if (!$course) {
            $this->error("课程不存在");
        }
        $student = Db::name("student")->where("user_id", $user_id)->find();
        if (!$student) {
            $this->error("当前用户不存在");
        }
        Db::startTrans();
        try {
            $mygoods = Db::name('order_car_item')->where('student_id', $student['id'])->where('course_id', $course_id)->find();
            if (!$mygoods) {
                throw new Exception('课程不在购物车内');
            }
            $carItem['student_id'] = $student['id'];
            $carItem['course_id'] = $course_id;
            Db::name('order_car_item')->where($carItem)->delete();
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->error($e->getMessage());
        }
        $this->success('移除成功');
    }


    /**
     * @Notes: 我的购物车
     * @Author: zhao
     * @Date: 2020/8/26
     * @Time: 11:32
     * @Interface mycar
     */
    public function mycar()
    {
        $courseId = input('course_id');
        $whereTwo = [];
        if(!empty($courseId)){
            $whereTwo['c.id'] = $courseId;
        }
        $user_id = $this->auth->id;
        $student = Db::name("student")->where("user_id", $user_id)->find();
        if (!$student) {
            $this->error('当前用户不存在');
        }
        $result = Db::name('order_car_item')
            ->alias('o')
            ->join('course c', 'o.course_id = c.id', 'LEFT')
            ->where('o.student_id', $student['id'])
            ->where($whereTwo)
            ->select();
        foreach ($result as $key => &$value) {
            $course = Db::name('teacher')->alias('t')
                ->where('t.id', $value['teacher_id'])
                ->field(['t.nick_name', 't.header'])
                ->find();
            unset($value['content']);
            $value['teacher'] = $course;
        }
        $this->success('OK', $result);
    }

    /**
     * @Notes:我的优惠券列表
     * @Author: zhao
     * @Date: 2020/8/26
     * @Time: 15:23
     * @Interface mycoupon
     */
    public function mycoupon()
    {
        $user_id = $this->auth->id;
        $page = input('page', '1');
        $size = input('size', '5');
        $student = Db::name("student")->where("user_id", $user_id)->find();
        if (!$student) {
            $this->error('当前用户不存在');
        }
        // 先将该用户超出时间的卷改变状态
        Db::name('coupon_user')
            ->where(['uid' => $student['id'], 'status' => 1])
            ->where('end_time', '<=', date('Y-m-d H:i:s'))
            ->update(['status' => 0]);
        $data = Db::name('coupon_user')
            ->where(['uid' => $student['id'], 'status' => 1])
            ->page($page, $size)
            ->select();
        $result = array('total' => count($data), 'data' => $data);
        $this->success('查询成功', $result);
    }

    /***
     * @Notes: 生成订单  生成订单 ,校验优惠券，锁定优惠券，是否已经购买过该课程，生成交易流水
     * 将课程和用户标识绑定放入order表
     * @Author: zhao
     * @Date: 2020/8/26
     * @Time: 11:26
     * @Interface createOrder
     */
    public function createOrder()
    {
        $param = $this->request->post();
        $user_id = $this->auth->id;
        $course_ids = $param['course_ids'];
        $address_id = $param['address_id'];
        if (empty($address_id)) {
            $this->error('收货地址不可为空');
        }
        $address = Db::name('address')->where('id', $address_id)->find();
        if (empty($address)) {
            $this->error('收货地址异常');
        }
        $course_id_array = explode(',', $course_ids);
        $student = Db::name("student")->where("user_id", $user_id)->find();
        $coupon = null;
        if (array_key_exists('coupon_id', $param) && $param['coupon_id']) {
            $mywhere['coupon_id'] = $param['coupon_id'];
            $mywhere['uid'] = $student['id'];
            $coupon = Db::name('coupon_user')->where($mywhere)->find();
        }
        $batch_id = 'B' . Util::createOnlyOrderNumber();
        Db::startTrans();
        $order_id = 0;
        $order_id_array = [];
        try {
            if (empty($course_id_array)) {
                throw new Exception('课程不能为空');
            }
            foreach ($course_id_array as $key => $value) {
                $course = Db::name('course')->where('id', $value)->find();
                if (!$course || !$student) {
                    throw new Exception('课程不存在');
                }

                $course_num = $course['course_num'];
                $student_num = $course['student_num'];
                if ($course['type_status'] == 1 && $student_num >= $course_num) {
                    throw new Exception('课程订购人数已满');
                }
                //校验是否已经购买过该课程
                $myOrderWhere['userId'] = $student['id'];
                $myOrderWhere['courseId'] = $value;
                $myOrderWhere['status'] = array('in', 'created,paid');
                $has = Db::name('order')->where($myOrderWhere)->find();
                if ($has) {
                    if ($has['status'] === 'created') {
                        throw new Exception($course['title'] . '订单已经创建，请支付');
                    }
                    throw new Exception($course['title'] . '已经报名了');
                }
                //校验优惠券是否可用
                if(!empty($coupon)){
                if ($coupon && ($coupon['status'] !== '1')) {
                    throw new Exception('当前优惠券不可用');
                } else if (time() >= strtotime($coupon['end_time'])) {
                    Db::name('coupon_user')->where('id', $coupon['id'])->update(['status' => 0]);
                    throw new Exception('当前优惠券不可用');
                }
                }
                //组装订单数据
                $order['coupon_id'] = $param['coupon_id'] ?? '';
                $order['courseId'] = $course['id'];
                $order['sn'] = Util::getOrderNumber();
                $order['userId'] = $student['id'];
                $order['create_time'] = Util::getNowDateTime();
                $order['title'] = $course['title'];
                $order['batch_id'] = $batch_id;
                $order['status'] = 'created';
                $order['address_id'] = $address_id;
                if ($course['is_promotion'] === '1') {
                    $order['price'] = $course['promotion_price'];
                } else {
                    $order['price'] = $course['price'];
                }
                $order['userId'] = $student['id'];

                //商品是否折扣
                if ($course['is_promotion'] === '1') {
                    $order['price'] = $course['promotion_price'];
                } else {
                    $order['price'] = $course['price'];
                }

                //锁定优惠券
                if ($key === 0 && $coupon) {
                    $order['coupon'] = $coupon['sn'];
                    $order['coupon_id'] = $coupon['coupon_id'];
                    $order['coupon_discount'] = $coupon['money'];
                    $coupon['status'] = '2';
                    Db::name('coupon_user')->update($coupon);
                    $order['amount'] = $order['price'] - $order['coupon_discount'];
                } else {
                    $order['amount'] = $order['price'];
                }
                Db::name('order')->insert($order);
                $order_id = Db::name('order')->getLastInsID();
                array_push($order_id_array, $order_id);
            }

            $carItem['student_id'] = $student['id'];
            $carItem['course_id'] = $value;
//                移除购物车
            $mygoods = Db::name('order_car_item')->where('student_id', $carItem['student_id'])->where('course_id', $carItem['course_id'])->find();
            if ($mygoods) {
                Db::name('order_car_item')->where($carItem)->delete();
            }

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            if ($e->getMessage()) {
                return $this->error($e->getMessage());
            }
        }

        $result = [];
        $result['order_id'] = $order_id;
        $result['batch_id'] = $batch_id;
        $course_array = [];
        if (!empty($order_id_array)) {
            foreach ($order_id_array as $key => $value) {
                $order = Db::name('order')->where('id', $value)->find();
                $course = Db::name('course')->alias('c')
                    ->join('teacher t', 'c.teacher_id = t.id')
                    ->where('c.id', $order['courseId'])
                    ->field(['c.id', 'c.title', 'c.subtitle', 'c.cover_image',
                        'c.expiry_start_time', 'c.expiry_end_time', 'c.section_num', 'c.type_status', 'c.course_num', 'c.student_num',
                        'price', 'c.difficulty', 'c.promotion_price', 'c.is_promotion', 't.name', 't.header'])
                    ->find();
                array_push($course_array, $course);
            }
            $result['course'] = $course_array;
        }
        return $this->success('创建成功', $result);
    }

    /**
     * @Notes:
     * @Author: zhao
     * @Date: 2020/8/26
     * @Time: 19:23
     * @Interface myorders
     */
    public function myorders()
    {
        $user_id = $this->auth->id;
        $student = Db::name("student")->where("user_id", $user_id)->find();
        if (!$student) {
            $this->error("当前用户不存在");
        }
        $map['userId'] = $student['id'];
        $row = Db::name('order')->where($map)->select();
        foreach ($row as $key => &$value) {
            $course = Db::name('course')->alias('c')
                ->join('teacher t', 'c.teacher_id = t.id')
                ->where('c.id', $value['courseId'])
                ->field(['c.id', 'c.title', 'c.subtitle', 'c.cover_image',
                    'c.expiry_start_time', 'c.expiry_end_time', 'c.section_num', 'c.type_status', 'c.course_num', 'c.student_num',
                    'price', 'c.difficulty', 'c.promotion_price', 'c.is_promotion', 't.name', 't.header'])
                ->find();
            if (empty($course)) {
                unset($value);
            } else {
                $value['detail'] = $course;
            }
        }
        $total = Db::name('order')->where($map)->count();
        $result = array('total' => $total, 'row' => $row);
        $this->success('OK', $result);
    }

    public function orderDetail()
    {
        $param = input();
        $order_id = $param['id'];
        $user_id = $this->auth->id;
        $student = Db::name("student")->where("user_id", $user_id)->find();
        if (!$student) {
            $this->error("当前用户不存在");
        }
        $map['userId'] = $student['id'];
        $map['id'] = $order_id;
        $order = Db::name('order')->where($map)->find();
        $courseId = $order['courseId'];
//        查询订单详情的地址
        $flow = Db::name('cash_flow')->where('batch_id', $order['batch_id'])->find();
        $address = array();
        if ($flow['address_id']) {
            $address = Db::name('address')->where('id', $flow['address_id'])->find();
        }
        $course = Db::name('course')->alias('c')
            ->join('teacher t', 'c.teacher_id = t.id')
            ->where('c.id', $courseId)
            ->field(['c.id', 'c.title', 'c.subtitle', 'c.cover_image',
                'c.expiry_start_time', 'c.expiry_end_time', 'c.section_num', 'c.type_status',
                'price', 'c.difficulty', 'c.promotion_price', 'c.is_promotion', 't.name', 't.header'])
            ->find();
        $result = array('course' => $course, 'order' => $order, 'address' => $address);
        $this->success('OK', $result);
    }

    /**
     * @Notes:
     * @Author: zhao
     * @Date: 2020/8/28
     * @Time: 15:40
     * @Interface refund退款
     *
     * 不可重复退款
     *
     *
     */
    public function refund()
    {
        $param = $this->request->post();
        try {
            Db::startTrans();
            $user_id = $this->auth->id;
            if (!$user_id) {
                throw new Exception('请先登录');
            }
            $order = Db::name('order')->where('sn', $param['sn'])->find();
            if (empty($order)) {
                throw new Exception('没找到订单');
            }
            if ('refunding' === $order['status']) {
                throw new Exception('已经提交退款');
            }
            $amount = $param['amount'];
            if ($amount > $order['amount']) {
                throw new Exception('退款不能超过商品原价');
            }
            $user = Db::name('student')->where('user_id', $user_id)->find();
            if (empty($user)) {
                throw new Exception('用户不存在');
            }
            $flow = Util::createOnlyOrderNumber();
            $cash_flow = [
                "sn" => $flow,
                "amount" => $amount,
                "type" => 'outflow',
                "name" => $order['title'],
                "batch_id" => $order['batch_id'],
                "create_time" => Util::getNowDateTime(),
                "userId" => $user['id']
            ];
            Db::name('cash_flow')->insert($cash_flow);
//            订单状态修改
            Db::name('order')->where('id', $order['id'])->setField('status', 'refunding');
//            提交退款
            $out_trade_no = $param['sn'];
            $out_refund_no = $flow;
            $total_fee = $amount * 100;
            $refund_fee = $amount * 100;
            $refund_desc = $order['title'] . '申请退款';
            $notify_url = $this->request->root(true) . '/api/Bizcommon/wechatNotifyxFund';
//            $res = Util::weChatRefund('J901291414373240','J901291414373240','1','1','测试',$this->request->root(true) .'/api/Bizcommon/wechatNotifyx');
            $res = Util::weChatRefund($out_trade_no, $out_refund_no, $total_fee, $refund_fee, $refund_desc, $notify_url);
            dump($res);
            Db::commit();
            return $this->success('处理成功', $res);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            if (!empty($e->getMessage())) {
                return $this->error($e->getMessage());
            }
        }
        return $this->success('操作成功');
    }

    /**
     * @Notes:
     * @Author: zhao
     * @Date: 2020/8/31
     * @Time: 12:13
     * @Interface refundBack
     * 退款回调
     * 1，修改订单状态，2退款订单流水状态
     */
    public function refundBack($order_sn)
    {
        Db::startTrans();
        try {

            if ($order_sn) {
                $order = Db::name('order')->where('batch_id', $order_sn)->find();
                //                todo 退款中才可以退款
                if ($order['status'] === 'refunding') {
                    $cash_flow = Db::name('cash_flow')->where('batch_id', $order['batch_id'])->find();
                    Db::name('order')->where('batch_id', $order_sn)->update(array('status' => 'refunded', 'refundId' => $cash_flow['id']));
                    Db::name('cash_flow')->where('batch_id', $order['batch_id'])->setField('status', '1');
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            if (!empty($e->getMessage())) {
                return $this->error($e->getMessage());
            }
        }
        return 'OK';

    }


    /**
     * @Notes:去支付 生成订单
     * 锁定订单--》lock；校验课程人数--》调用支付接口
     * 30分钟后不支付，则默认取消订单
     * 支付成功回调：
     * 生成支付流水；修改订单状态 paied；若有优惠券则修改状态3已使用
     *
     * @Author: zhao
     * @Date: 2020/8/27
     * @Time: 10:16
     * @Interface toPay
     *  order_id
     *  pay_type  alipay', 'wechat'
     *  flow 流水类型:inflow=入账,outflow=退款
     */
    public function toPay()
    {
        $baseUrl = Env::get('app.baseUrl', 'http://by.21bmw.com');
        $order_id = input("order_id");
        $pay_type = input("pay_type", "wechat");
        $refundurl = input("refundurl", $baseUrl . "/settlementCenter?stepsNum=2");
        $method = input('method', 'web');
        $flow_type = 'inflow';
        if (!$order_id || !$pay_type) {
            return $this->error('传入参数为空');
        }
        $order = Db::name('order')->where('id', $order_id)->find();
        if (!$order) {
            return $this->error('没有找到对应的订单');
        }
        $res = null;
        if ('alipay' === $pay_type) {
            $res = $order['pay_code_ali'];
        } else {
            $res = $order['pay_code_wei'];
        }
        $result = array();
        $order_amount_array = Db::name('order')->where('batch_id', $order['batch_id'])->field('amount')->select();
        $order_sum = array_sum(array_column($order_amount_array, 'amount'));
        Db::startTrans();
        try {
            // 生成资金流水
            $flow = Util::getOrderNumber();
            $cash_flow = [
                "userId" => $order['userId'],
                "sn" => $flow,
                "amount" => $order_sum,
                "type" => $flow_type,
                "name" => $order['title'] . '...',
                "batch_id" => $order['batch_id'],
                "create_time" => Util::getNowDateTime(),
            ];
            //            插入地址
            $address = Db::name('address')->where('type', 'student')->where('uid', $order['userId'])->find();
            if ($address) {
                $cash_flow['address_id'] = $address['id'];
            }
//           插入流水
            Db::name('cash_flow')->insert($cash_flow);
            $mycourse = Db::name('course')->where('id', $order['courseId'])->find();
            $course_num = $mycourse['course_num'];
            $student_num = $mycourse['student_num'];
            if ($mycourse['type_status'] == '1' && $student_num >= $course_num) {
                throw new Exception('课程订购人数已满');
            }
            $params = [
                'type' => $pay_type,
                'out_trade_no' => $order['batch_id'],
                'title' => $order['title'] . '...',
                'amount' => $order_sum,
                'method' => $method
            ];
            Util::write_log(json_encode($params, JSON_UNESCAPED_UNICODE));
            $notifyurl = $this->request->root(true) . '/api/Bizcommon/wechatNotifyx/type/' . $pay_type;
            $res = Service::submitOrder($params['amount'],
                $params['out_trade_no'],
                $params['type'],
                $params['title'],
                $notifyurl,
                $refundurl,
                $method);
            $mymap['status'] = 'lock';
            $mymap['payment'] = $pay_type;
            $mymap['cash_sn'] = $flow;
            if ('alipay' === $pay_type) {
                $mymap['pay_code_ali'] = $res;
            } else {
                $mymap['pay_code_wei'] = $res;
            }
            Db::name('order')->where('batch_id', $order['batch_id'])->update($mymap);
            Db::commit();
            //生成支付二维码
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->error($e->getMessage());
        }

        $result['code'] = $res;
        $result['amount'] = $order_sum;
        $result['batch_id'] = $order['batch_id'];
        $result['time'] = $order['create_time'];
        return $this->success('OK', $result);
    }

    /** 支付回调处理
     *  支付流水状态 status 1；修改订单状态 paied；若有优惠券则修改状态3已使用
     * @Notes:
     * @Author: zhao
     * @Date: 2020/8/27
     * @Time: 11:24
     * @Interface payNotify
     */
    public function payNotify($order_sn)
    {
        if ($order_sn) {
            $order = Db::name('order')->where('batch_id', $order_sn)->select();
//            交易订单是否锁定
            Db::startTrans();
            try {
                Db::name('order')->where('batch_id', $order_sn)->update(array('status' => 'paid', 'paid_time' => Util::getNowDateTime()));
                Db::name('cash_flow')->where('batch_id', $order_sn)->setField('status', '1');
                foreach ($order as $key => $value) {
                    if ($key === 0) {
                        Db::name('course')->where('id', $value['courseId'])->setInc('student_num', 1);
                    }
                    if ($value['coupon_id']) {
                        Db::name('coupon_user')->where('coupon_id', $order['coupon_id'])->setField('status', '3');
                    }
//                    支付回调分销处理
                    $hooks_data = [
                        'orderID' => $value['id'],
                    ];
                    Hook::listen("commonDistribution", $hooks_data);
                }
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                Util::write_log(json_encode($e->getMessage(), JSON_UNESCAPED_UNICODE));
            }
        }
    }

    /**
     * @Notes:
     * @Author: zhao
     * @Date: 2020/9/9
     * @Time: 15:25
     * @Interface checkOrders
     * 定时检查订单，若超过30分钟没有支付，则取消订单
     * 校验订单创建时候和当前时间是否已经超过30分钟，若超过30分钟未支付则取消订单，修改流水和订单状态，同时释放订单上的优惠券。
     */
    public function checkOrders()
    {
        $batchLists = Db::name('cash_flow')->where('status', 0);
        foreach ($batchLists as $key => $value) {
            $create = strtotime($value['create_time']);
            $now = strtotime(Util::getNowDateTime());
//            超过30分钟
            if (($now - $create) / (60) >= 30) {
                $this->dealBatchCancle($value['batch_id']);
            }

        }
    }


    /**
     * @Notes: 取消订单
     * 设置当前订单状态 cancelled，若有优惠券则设置优惠券的状态为1（可用），修改课程订购人数
     * @Author: zhao
     * @Date: 2020/8/27
     * @Time: 10:16
     * @Interface toCancle
     */
    public function toCancle($order_sn)
    {
        if ($order_sn) {
            try {
                Db::startTrans();
                $myorder = Db::name('order')->where('sn', $order_sn)->find();

                if ('cancelled' === $myorder['status']) {
                    throw new Exception('订单已经取消');
                }
                if ($myorder) {
                    Db::name('order')->where('sn', '=', $order_sn)->setField('status', 'cancelled');
                    if ($myorder['coupon_id']) {
                        Db::name('coupon_user')->where('coupon_id', $myorder['coupon_id'])->setField('status', '1');
                    }
                    Db::name('cash_flow')->where('order_id', $myorder['id'])->setField('status', '3');
                }
                Db::commit();
                return $this->success('操作成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->error($e->getMessage());
            }
        }
    }

    /**
     * @Notes:
     * @Author: zhao
     * @Date: 2020/9/9
     * @Time: 16:37
     * @Interface dealBatchCancle
     * @param $batch_id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 取消订单逻辑
     */
    private function dealBatchCancle($batch_id)
    {
        if ($batch_id) {
            Db::name('cash_flow')->where('order_id', $batch_id)->setField('status', '3');
            $orders = Db::name('order')->where('batch_id', $batch_id)->select();
            Db::name('order')->where('batch_id', $batch_id)->setField('status', 'cancelled');
            if ($orders) {
                foreach ($orders as $key => $value) {
                    if ($value['coupon_id']) {
                        Db::name('coupon_user')->where('coupon_id', $value['coupon_id'])->setField('status', '1');
                    }
                }
            }
        }
    }


    /** 测试
     * @Notes:
     * @Author: zhao
     * @Date: 2020/8/31
     * @Time: 09:53
     * @Interface testCancle
     */
    public function testCancle()
    {

        $param = $this->request->post();
        $order_sn = $param['order_sn'];
        return $this->toCancle($order_sn);
    }

    public function testPay()
    {

        $param = $this->request->post();
        $order_sn = $param['order_sn'];
        return $this->payNotify($order_sn);
    }


    public function testNotify()
    {
        $param = $this->request->post();
        $order_sn = $param['order_sn'];
        return $this->payNotify($order_sn);
    }

    public function testRefund()
    {
        $param = $this->request->post();
        $order_sn = $param['order_sn'];
        return $this->refundBack($order_sn);
    }
}